#include "sqlite3/sqlite3.h"

#include <stdio.h>
#include <stdlib.h>

// 教程地址 https://www.cnblogs.com/findumars/p/9048286.html

int sql_select_cb(void *userdata, int n_column, char **column_value, char **column_name)
{
    // userdata 用户传入的数据
    // n_column 查询的字段长度 column_value数组长度
    // column_value char *数组 键
    // column_name char *数组 字段名

    int i = 0;
    printf("查询字段数量:%d\n", n_column);
    for (; i < n_column; i++)
    {
        printf("name:%s value:%s\n", column_name[i], column_value[i]);
    }
    printf("==========\n");
    return 0;
}

// 编译命令 gcc main.c sqlite3/sqlite3.c -I./sqlite3 -o main -lpthread -ldl
int main(void)
{
    sqlite3 *db;
    int res = 0;
    char *errmsg = NULL;
    // 打开某个数据库文件
    res = sqlite3_open("test.db", &db);
    if (res != SQLITE_OK)
    {
        printf("open db fail!\n");
    }
    res = sqlite3_exec(db, "create table if not exists MyTable_1(id integer primary key autoincrement,name nvarchar(32))", NULL, NULL, &errmsg);
    if (res != SQLITE_OK)
    {
        printf("create table fail! errcode:%d errmsg:%s\n", res, errmsg);
    }
    // 插入数据
    res = sqlite3_exec(db, "insert into MyTable_1(name) values('刀')", NULL, NULL, &errmsg);
    if (res != SQLITE_OK)
    {
        printf("insert data fail! errcode:%d errmsg:%s\n", res, errmsg);
    }
    res = sqlite3_exec(db, "insert into MyTable_1(name) values('剑')", NULL, NULL, &errmsg);
    if (res != SQLITE_OK)
    {
        printf("insert data fail! errcode:%d errmsg:%s\n", res, errmsg);
    }

    // 使用回调查询数据
    // res = sqlite3_exec(db, "select * from MyTable_1", sql_select_cb, NULL, &errmsg);
    // if (res != SQLITE_OK)
    // {
    //     printf("select data fail! errcode:%d errmsg:%s\n", res, errmsg);
    // }
    char **datas; // 一维数组（扁平化的数组）
    int nRow;     // 查询出行数
    int nCol;     // 查询出列数
    /*
            nCol0; nCol1;
    nRow0;
    nRow1;
    nRow2;
    nRow3;
    */
    res = sqlite3_get_table(db, "select * from MyTable_1", &datas, &nRow, &nCol, &errmsg);
    if (res != SQLITE_OK)
    {
        printf("select data fail! errcode:%d errmsg:%s\n", res, errmsg);
    }
    else
    {
        int index = nCol;
        int i = 0;
        int j = 0;
        for (; i < nRow; i++)
        {
            for (j = 0; j < nCol; j++)
            {
                printf("字段名:%s 字段值:%s\n", datas[j], datas[index]);
                index++;
            }
            printf("========\n");
        }
        sqlite3_free_table(datas);
        datas = NULL;
    }

    sqlite3_close(db);
    return 0;
}